package com.supersit.greensproject.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.supersit.greensproject.Amap.AMap_LocationUtils;
import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.entity.Coordinate;
import com.supersit.greensproject.entity.MaketSubject;
import com.supersit.greensproject.utils.NetUtils;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.CustomDialog;
import com.supersit.greensproject.view.MyTitleBar;
import com.supersit.greensproject.view.ShowDialog;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by cong on 2016/7/18.
 */
@ContentView(R.layout.activity_maket_subject_entering)
public class MaketSubjectEnteringActivity extends BaseActivity {
    private Context context;
    private MyTitleBar myTitleBar;
    @ViewInject(R.id.sp_maket_entering_area)
    private Spinner spArea;
    private String[] areas;
    private String aresStr;
    @ViewInject(R.id.et_entering_data)
    private EditText etCreateDate;
    @ViewInject(R.id.et_maket_name)
    private EditText etMaketName;
    @ViewInject(R.id.et_maket_address)
    private EditText etMaketAddress;
    @ViewInject(R.id.et_maket_contacts)
    private EditText etContacts;
    @ViewInject(R.id.et_maket_tel)
    private EditText etTel;
    @ViewInject(R.id.ib_addCoordinates)
    private ImageButton ibAddCoordinate;//增加坐标
    @ViewInject(R.id.ib_show_polygon)
    private ImageButton ibShowPolygon;//地图显示
    @ViewInject(R.id.save_maket)
    private Button btnSave;
    @ViewInject(R.id.lv_coordinates_list)
    private LinearLayout lvCoordinate;//坐标列表
    @ViewInject(R.id.sp_maket_entering_type)
    private Spinner spMaketType;//市场类型
    @ViewInject(R.id.et_business_licence)
    private EditText etBusinessLicence;//营业执照
    private List<Coordinate> coordinates;
    private AMap_LocationUtils locationUtils;
    private int coordinateCount;
    private MaketSubject ms;
    private int maketFlag;//标记数据类型 0新增  1修改
    private boolean isUpdate = false;
    private int updateCoordinateItem = 0;
    private ShowDialog showDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        context = this;
        setTitleBar();
        initVariable();
        bindListener();
        setData();

    }

    private void setTitleBar() {
        myTitleBar = new MyTitleBar(context, findViewById(R.id.maket_subject_entering_title));
        myTitleBar.setTitleText(context.getResources().getString(R.string.maket_subject_entering_title));
        myTitleBar.setChildVisibility(false, myTitleBar.getmImgRight());
    }

    private void bindListener() {
        myTitleBar.setImg1Listener(onClickListener);
        spArea.setOnItemSelectedListener(onItemSelectedListener);
        spMaketType.setOnItemSelectedListener(onItemSelectedListener);
        ibAddCoordinate.setOnClickListener(onClickListener);
        ibShowPolygon.setOnClickListener(onClickListener);
        btnSave.setOnClickListener(onClickListener);

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.title_bar_left:
                    finish();
                    break;

                case R.id.ib_addCoordinates:
                    if (NetUtils.isConnected(context)) {
                        locationUtils.startLocation();
                        ibAddCoordinate.setEnabled(false);
                        showDialog.showLoadingDialog(getString(R.string.locationing));
                    } else {
                        T.showShort(context, R.string.net_not_connected);
                    }
                    break;
                case R.id.ib_show_polygon:
                    if (coordinates.size() < 3) {
                        T.showShort(context, R.string.base_coordinate_is_null);
                    } else {
                        Intent showPolygoniItent = new Intent(context, AMapPolygonActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("coordinates", (Serializable) coordinates);
                        showPolygoniItent.putExtras(bundle);
                        context.startActivity(showPolygoniItent);
                    }
                    break;
                case R.id.save_maket:
                    if (checkData()) {
                        String createDate = TextUtils.isEmpty(etCreateDate.getText().toString()) ? "" : etCreateDate.getText().toString().trim();
                        String businessLicence = TextUtils.isEmpty(etBusinessLicence.getText().toString()) ? "" : etBusinessLicence.getText().toString().trim();
                        int aeraId = spArea.getSelectedItemPosition();
                        int maketType = spMaketType.getSelectedItemPosition();
                        String maketName = TextUtils.isEmpty(etMaketName.getText().toString()) ? "" : etMaketName.getText().toString().trim();
                        String maketAddress = TextUtils.isEmpty(etMaketAddress.getText().toString()) ? "" : etMaketAddress.getText().toString().trim();
                        String contacts = TextUtils.isEmpty(etContacts.getText().toString()) ? "" : etContacts.getText().toString().trim();
                        String tel = TextUtils.isEmpty(etTel.getText().toString()) ? "" : etTel.getText().toString().trim();
                        StringBuffer longitudes = new StringBuffer();//经度
                        StringBuffer latitudes = new StringBuffer();//纬度
                        for (int i = 0; i < coordinates.size(); i++) {
                            if (i == (coordinates.size() - 1)) {
                                longitudes.append(coordinates.get(i).getLongitude() + "");
                                latitudes.append(coordinates.get(i).getLatitude() + "");
                            } else {
                                longitudes.append(coordinates.get(i).getLongitude() + ",");
                                latitudes.append(coordinates.get(i).getLatitude() + ",");
                            }
                        }
                        ms.setCreateDate(createDate);
                        ms.setBusinessLicence(businessLicence);
                        ms.setAreaId(aeraId);
                        ms.setCategory(maketType);//市场类型 0批发市场  1零售市场
                        ms.setMaketName(maketName);
                        ms.setMaketAddress(maketAddress);
                        ms.setOperator(contacts);//经营者 /联系人
                        ms.setTel(tel);
                        ms.setLatitudes(latitudes.toString());
                        ms.setLongitudes(longitudes.toString());
                        ms.setIsDelete(1);//是否删除（icv1：正常 0：删除）
                        DbManager db =db = XUtilsDbManager.getInstance();
                        if (0 == maketFlag) {//0新增 1修改
                            ms.setOperationsTatus(1);//操作状态(0：删除；1：新增；1：修改,-1正常)
                            try {
                                db.saveBindingId(ms);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        } else if (1 == maketFlag) {
                            ms.setOperationsTatus(2);
                            try {
                                db.update(ms);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                        T.showShort(context, R.string.save_ok);
                        finish();
                    }
                    break;
            }
        }
    };

    private void initVariable() {
        ArrayAdapter areaAdapter = ArrayAdapter.createFromResource(
                context, R.array.area, R.layout.spinner_text);
        areaAdapter.setDropDownViewResource(R.layout.item_spinner);
        spArea.setAdapter(areaAdapter);
        ArrayAdapter typeAdapter = ArrayAdapter.createFromResource(
                context, R.array.maket_type, R.layout.spinner_text);
        typeAdapter.setDropDownViewResource(R.layout.item_spinner);
        spMaketType.setAdapter(typeAdapter);
        spMaketType.setEnabled(false);
        spMaketType.setClickable(false);
        areas = getResources().getStringArray(R.array.area);
        showDialog = new ShowDialog(context);
        locationUtils = new AMap_LocationUtils(context, getResult);
        coordinates = new ArrayList<Coordinate>();
    }

    private AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            aresStr = areas[position];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    /**
     * 定位回调接口
     */
    private AMap_LocationUtils.GetResult getResult = new AMap_LocationUtils.GetResult() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            showDialog.dismissLoadDialog();
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    final double latitude = amapLocation.getLatitude();//获取纬度
                    final double longitude = amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);//定位时间
                    amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    amapLocation.getCountry();//国家信息
                    amapLocation.getProvince();//省信息
                    amapLocation.getCity();//城市信息
                    amapLocation.getDistrict();//城区信息
                    amapLocation.getStreet();//街道信息
                    amapLocation.getStreetNum();//街道门牌号信息
                    amapLocation.getCityCode();//城市编码
                    amapLocation.getAdCode();//地区编码
                    amapLocation.getAoiName();//获取当前定位点的AOI信息
                    if (isUpdate) {
                        if (updateCoordinateItem >= 0) {
                            coordinates.get(updateCoordinateItem).setLatitude(latitude);
                            coordinates.get(updateCoordinateItem).setLongitude(longitude);
                            reapplication(coordinates);
                            ibAddCoordinate.setEnabled(true);
                            isUpdate = false;
                        }
                    } else {
                        CustomDialog dialog;
                        CustomDialog.Builder customBuilder = new CustomDialog.Builder(
                                context);
                        customBuilder
                                .setTitle(R.string.location_affirm)
                                .setMessage("经度:" + longitude + "\n纬度:" + latitude)
                                .setNegativeButton(R.string.ok,
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                                int which) {
                                                if (null != coordinates && coordinates.size() > 0) {
                                                    ++coordinateCount;
                                                }
                                                //T.showShort(context, "NegativeButton");
                                                Coordinate coordinate = new Coordinate();
                                                coordinate.setLatitude(latitude);
                                                coordinate.setLongitude(longitude);
                                                View view = LayoutInflater.from(context).inflate(R.layout.item_coordinate_list, null);
                                                TextView lon = (TextView) view.findViewById(R.id.tv_item_longinude);
                                                TextView lag = (TextView) view.findViewById(R.id.tv_item_latitude);
                                                TextView num = (TextView) view.findViewById(R.id.tv_item_num);
                                                Button removeCoordinate = (Button) view.findViewById(R.id.btn_remove_coordinate);
                                                lon.setText("经度" + coordinate.getLongitude() + "");
                                                lag.setText("纬度" + coordinate.getLatitude() + "");
                                                num.setText((coordinateCount + 1) + "");
                                                view.setTag(coordinateCount + 1);
                                                coordinateStatuListener(removeCoordinate, (Integer) view.getTag());
                                                lvCoordinate.addView(view);
                                                coordinates.add(coordinate);
                                                ibAddCoordinate.setEnabled(true);
                                                dialog.dismiss();
                                            }
                                        })
                                .setPositiveButton(R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                                int which) {
                                                //  T.showShort(context, "PositiveButton");
                                                ibAddCoordinate.setEnabled(true);
                                                dialog.dismiss();
                                            }
                                        });
                        dialog = customBuilder.create();
                        dialog.show();

                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    CustomDialog dialog;
                    CustomDialog.Builder customBuilder = new CustomDialog.Builder(
                            context);
                    customBuilder
                            .setTitle(R.string.location_fail)
                            .setMessage("ErrCode:"
                                    + amapLocation.getErrorCode() + "\n errInfo:"
                                    + amapLocation.getErrorInfo())
                            .setNegativeButton(R.string.ok,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            dialog.dismiss();
                                        }
                                    });
                    dialog = customBuilder.create();
                    dialog.show();
                }
            } else {
                T.showShort(context, R.string.location_fail);
            }
            locationUtils.stopLocation();
        }
    };

    private void setData() {
        Intent it = getIntent();
        maketFlag = it.getIntExtra("maketFlag", 0);//标记数据 0新增 1修改
        int maketTypeFlag = it.getIntExtra("maketType", 0);
        if (1 == maketFlag) {
            Bundle bundle = it.getExtras();
            if (null != bundle) {
                ms = (MaketSubject) bundle.getSerializable("maketsubject");
                spArea.setSelection(ms.getAreaId());
                etCreateDate.setText(ms.getCreateDate() == null ? "" : ms.getCreateDate());
                etBusinessLicence.setText(ms.getBusinessLicence() == null ? "" : ms.getBusinessLicence());
                etMaketName.setText(ms.getMaketName() == null ? "" : ms.getMaketName());
                spMaketType.setSelection(ms.getCategory() == 0 ? 0 : ms.getCategory());
                spMaketType.setEnabled(true);
                spMaketType.setClickable(true);
                etMaketAddress.setText(ms.getMaketAddress() == null ? "" : ms.getMaketAddress());
                etContacts.setText(ms.getOperator() == null ? "" : ms.getOperator());
                etTel.setText(ms.getTel() == null ? "" : ms.getTel());
                String[] Longitudes = TextUtils.isEmpty(ms.getLongitudes()) ? null : ms.getLongitudes().split(",");
                String[] Latitudes = TextUtils.isEmpty(ms.getLatitudes()) ? null : ms.getLatitudes().split(",");
                if (null != Latitudes && null != Longitudes) {
                    for (int x = 0; x < Latitudes.length; x++) {
                        Coordinate coordinate = new Coordinate();
                        coordinate.setLatitude(Double.parseDouble(Latitudes[x]));
                        coordinate.setLongitude(Double.parseDouble(Longitudes[x]));
                        coordinates.add(coordinate);
                        coordinateCount = x;
                    }
                    reapplication(coordinates);
                }
            }
        } else {
            etCreateDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            etCreateDate.setEnabled(false);
            ms = new MaketSubject();
            // T.showShort(context, maketTypeFlag + "");
            spMaketType.setSelection(maketTypeFlag);
        }
    }

    private boolean checkData() {
        boolean flag = false;

        if (TextUtils.isEmpty(etCreateDate.getText().toString().trim())) {
            T.showShort(context, R.string.maket_create_is_null);
            return flag;
        }
        if (TextUtils.isEmpty(etMaketName.getText().toString().trim())) {
            T.showShort(context, R.string.MakteName_is_not_null);
            return flag;
        }

        if (TextUtils.isEmpty(etMaketAddress.getText().toString().trim())) {
            T.showShort(context, R.string.MaketAddress_is_not_null);
            return flag;
        }
//        if (TextUtils.isEmpty(etContacts.getText().toString().trim())) {
//            T.showShort(context, R.string.Contacts_is_not_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etTel.getText().toString().trim())) {
//            T.showShort(context, R.string.Tel_is_not_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etBusinessLicence.getText().toString().trim())) {
//            T.showShort(context, R.string.maket_business_licence_is_null);
//            return flag;
//        }

        if (null == coordinates || coordinates.size() < 3) {
            T.showShort(context, R.string.maket_coordinate_is_null);
            return flag;
        }
        flag = true;
        return flag;
    }

    /**
     * 刷新座標
     */
    private void reapplication(List<Coordinate> coordinates) {
        if (null != coordinates && coordinates.size() > 0) {
            lvCoordinate.removeAllViews();
            coordinateCount = 0;
            for (int x = 0; x < coordinates.size(); x++) {
                View view = LayoutInflater.from(context).inflate(R.layout.item_coordinate_list, null);
                TextView lon = (TextView) view.findViewById(R.id.tv_item_longinude);
                TextView lag = (TextView) view.findViewById(R.id.tv_item_latitude);
                TextView num = (TextView) view.findViewById(R.id.tv_item_num);
                Button removeCoordinate = (Button) view.findViewById(R.id.btn_remove_coordinate);
                Coordinate coordinate = coordinates.get(x);
                lon.setText("经度" + coordinate.getLongitude());
                lag.setText("纬度" + coordinate.getLatitude());
                num.setText((x + 1) + "");
                view.setTag(x + 1);
                coordinateStatuListener(removeCoordinate, (Integer) view.getTag());
                lvCoordinate.addView(view);
                //   coordinates.add(coordinate);
                coordinateCount = x;
            }
        }
    }

    /**
     * 刪除或者修改座標狀態監聽
     *
     * @param removeCoordinate
     */
    private void coordinateStatuListener(Button removeCoordinate, final int viewTag) {
        removeCoordinate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(context).setTitle(R.string.remove_coordinate_title)
                        .setMessage(String.format(context.getString(R.string.is_remove_coordinate), viewTag + ""))
                        .setPositiveButton(R.string.update_coordinate, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                updateCoordinateItem = viewTag - 1;
                                isUpdate = true;
                                if (NetUtils.isConnected(context)) {
                                    locationUtils.startLocation();
                                    ibAddCoordinate.setEnabled(false);
                                    showDialog.showLoadingDialog(getString(R.string.locationing));
                                } else {
                                    T.showShort(context, R.string.net_not_connected);
                                }
                            }
                        })
                        .setNegativeButton(R.string.remove_coordinate, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                coordinates.remove(viewTag - 1);
                                reapplication(coordinates);
                            }
                        }).show();
            }
        });
    }
}
